package com.dminvoicemanager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class DM_Expense_Reimbursement extends Activity {

	// private PBDatabaseAdapter dbHelper;
	ProgressDialog mProgressDialog;
	private String DBNAME = "dminvoicemanager.db";
	// Master Tables
	private String SERVER_DB_LIST = "serverdb";
	private String USER_SETTINGS = "usersettings";
	private String ITEM_AREA = "fArea";
	private String ITEM_COMPANY_SETTING = "fCompanySetting";
	private String ITEM_CONTROL = "fControl";
	private String ITEM_DEBTOR = "fDebtor";
	private String ITEM_LOC_DETAILS = "fItemLoc";
	private String ITEM_LOCATION = "fLocation";
	private String ITEM_PRICE = "fItemPri";
	private String ITEMS = "fItems";
	private String INV_COMPANY_BRANCH = "FCompanyBranch";
	private String INV_SAL_REP = "fSalRep";
	private String SALES_ORD_REASON = "fReason";
	private String SALES_REP_ROUTE = "fRoute";
	private String BANK_DETAILS = "fBank";
	private String USER_EXPENSE = "fExpense";

	// Main Invoice
	private String TEMP_REP_INVOICESUMERY = "frepInvoiceSumery";
	private String INV_DETAILS = "FinvDet";
	private String INV_HEADER = "FinvHed";

	// Stock Loading
	private String TEMP_STOCK_LOADING_SUMMARY = "frepStockLoadingSummary";
	private String STOCK_LOAD_HEAD = "fLoadhed";
	private String STOCK_LOAD_DETAIL = "fLoadDet";

	// Stock Loading
	private String STOCK_ORDER_INVOICESUMERY = "fstockordInvoiceSumery";
	private String STOCK_ORDER_HEAD = "FOrdHed";
	private String STOCK_ORDER_DETAIL = "FOrddet";
	private String TEMPSTOCK_ORDER_HEAD = "TempFOrdHed";
	private String TEMPSTOCK_ORDER_DETAIL = "TempFOrddet";

	// Stock UnLoading
	private String TEMP_STOCK_LOADING_SUMMARYUN = "frepStockLoadingSummaryUn";
	private String STOCK_LOAD_HEADUN = "fUnLoadhed";
	private String STOCK_LOAD_DETAILUN = "fUnLoadDet";

	// Stock Damage
	private String TEMP_STOCK_LOADING_SUMMARYDAM = "frepStockLoadingSummaryDam";
	private String STOCK_LOAD_HEADDAM = "fDamhed";
	private String STOCK_LOAD_DETAILDAM = "fDamdet";

	// Cash /Receipt header
	private String TEMP_RECEIPT_SUMMARY = "fReceiptSummary";
	private String RECEIPT_HEADER = "fDRecHed";
	private String RECEIPT_DETAILS = "fDRecDet";

	// Adjustment
	private String TEMP_ADJUSTMENT_SUMMARY = "FAdjustmentSummary";
	private String ADJUST_ADDITION_HEADER = "FAdjHed";
	private String ADJUST_ADDITION_DETAILS = "FAdjDet";

	// Expense
	private String TEMP_DAYEXPENSE_SUMMARY = "FDayExpSummary";
	private String DAYEXPENSE_HEADER = "FDayExpHed";
	private String DAYEXPENSE_DETAILS = "FDayExpDet";
	private SQLiteDatabase mydb;
	Button etexpenseremfno, btdmexpenseremselect, dmexpenseremadd,
			dmexpenseremdelete, dmexpenseremupdate;
	EditText etdmexpenseremdate, etdmexpenseremremark, etdmexpenseremname,
			etdmexpenseremamount;

	String TagId, currentUserStLoad, currentUserPrefixLoad,
			currentUserLocation, stlAgentPrefixType, StlTransTypePrefix,
			tempRepExpenseSerialStr, ExpenseDetSummary, ExpenseCode,
			currentExpenseRefCode, RepExpenseCode, currentSequence,
			ExpenseRecordSummary, ExpenseRecid, tempdexpRefnoSerial,
			repDealCode, deviceUser = "ANDROID";
	LinearLayout dmexpensereimList, dmstexpensereimdetails,
			dmstloadActionButtons;
	int SAVETAG = 0, UPDATETAG = 0, DELTAG = 0, countC = 44, CLEARTAG = 0,
			CANCELTAG = 0, EXPENCESCHK = 0, ButtonTag, STOCKITEMSCHK = 0,
			EXITTAG = 0;
	double TotExpenseAmountSummary = 0.0;
	AlertDialog StockLoadingAlert = null;
	final private static int DIALOG_SAVE_STOCK_LOADING = 1;
	final private static int DIALOG_CANCEL_STOCK_LOADING = 2;
	final private static int DIALOG_UNDO_STOCK_LOADING = 3;
	final private static int DIALOG_PRINT_STOCK_LOADING = 4;
	private static final String TAG = null;

	public void BackToMainMenu(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();

	}

	// ****Back to main screen from expense list
	public void btnExpenseListBack(View view) {
		dmexpensereimList.setVisibility(view.GONE);
		dmstexpensereimdetails.setVisibility(view.VISIBLE);
		dmstloadActionButtons.setVisibility(view.VISIBLE);
	}

	// ****Set Expense Items in to main Screen******
	public void AddExpenseDetails(View view) {
		Button des = (Button) view;
		ExpenseDetSummary = des.getText().toString();
		String[] Locationsdetail = ExpenseDetSummary.split("/");
		ExpenseCode = Locationsdetail[0]; // ExpenseCode
		String ExpenseName = Locationsdetail[2]; // ExpenseName
		etdmexpenseremname.setText(ExpenseName);

		dmexpensereimList.setVisibility(view.GONE);
		dmstexpensereimdetails.setVisibility(view.VISIBLE);
		dmstloadActionButtons.setVisibility(view.VISIBLE);
	};

	// ****Dislay current expense details From List******
	public void ShowExpenseListDetails(View view) {
		Button des = (Button) view;
		ExpenseRecordSummary = des.getText().toString();
		String[] ExpenseRecord = ExpenseRecordSummary.split("-");
		ExpenseRecid = ExpenseRecord[0]; // expenseid
		String TxnDate = ExpenseRecord[1]; // TxnDate
		String ExpenseAmtP = ExpenseRecord[2]; // ExpName
		String ExpName = ExpenseRecord[3]; // Amt
		Log.v(TAG, "EXP :"+ExpenseRecid+"/"+TxnDate+"/"+ExpenseAmtP+"/"+ExpName);
		etdmexpenseremdate.setText(getCurrentTimeString().toString());
		etdmexpenseremname.setText(ExpName);
		etdmexpenseremamount.setText(ExpenseAmtP);
		dmexpenseremdelete.setEnabled(true);
		dmexpenseremupdate.setEnabled(true);
		dmexpenseremadd.setEnabled(false);
	};

	// Save Stock details and invoice header details to activate invoice
	public void btnSaveLoding(View view) {
		checkExpencesAvailable();
		if (EXPENCESCHK == 101) {
			ButtonTag = 2;
			SaveMainExpenseReimbursment();
		} else if (EXPENCESCHK == 102) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_Expense_Reimbursement.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("ITEMS LOAD");
			// Setting Dialog Message
			alertDialog.setMessage("No Expense Entered");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}

	}

	private void checkExpencesAvailable() {
		// TODO Auto-generated method stub
		String currentStLoadCodeRef = etexpenseremfno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor curChkItems = null;
		try {
			curChkItems = mydb.query(DAYEXPENSE_DETAILS, null, "RefNo='"
					+ currentStLoadCodeRef + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (curChkItems != null) {
			if (curChkItems.getCount() > 0) {
				EXPENCESCHK = 101;
			} else {
				EXPENCESCHK = 102;
			}
		}
		curChkItems.close();
		mydb.close();
	}

	private void SaveMainExpenseReimbursment() {
		// TODO Auto-generated method stub
		int DELTAG = 0;
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor saveExpenseRecordMain = null;
		try {
			saveExpenseRecordMain = mydb.query(TEMP_DAYEXPENSE_SUMMARY, null,
					"dexprepusername='" + currentUserStLoad
							+ "' AND dexpreActive='9'", null, null, null, null);
		} catch (Exception e) {
		}
		if (saveExpenseRecordMain != null) {
			if (saveExpenseRecordMain.getCount() > 0) {
				while (saveExpenseRecordMain.moveToNext()) {
					ContentValues valueupdateExpenseSumary = new ContentValues();
					String ExpenseRefCode = saveExpenseRecordMain.getString(7);

					String tempdexpRefnoSerialStr = saveExpenseRecordMain
							.getString(4);
					int tempdexpRefnoSerialVal = Integer
							.parseInt(tempdexpRefnoSerialStr);
					int newtempdexpRefnoSerialVal = tempdexpRefnoSerialVal + 1;
					tempRepExpenseSerialStr = Integer
							.toString(newtempdexpRefnoSerialVal);

					valueupdateExpenseSumary.put("dexpreComplete", "2");
					valueupdateExpenseSumary.put("dexpreActive", "0");
					mydb.update(TEMP_DAYEXPENSE_SUMMARY,
							valueupdateExpenseSumary, "dexprefnocode ='"
									+ ExpenseRefCode + "'", null);
					if (ButtonTag == 2) {
						try {
							showDialog(DIALOG_SAVE_STOCK_LOADING);
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}

				}

			}
		}
		saveExpenseRecordMain.close();
		mydb.close();

	}

	// ***********Expense Save Completed***************
	public void btnSaveInvoiceAccept(View view) {
		if (etexpenseremfno.length() != 0) {
			saveTempExpenseReimbursement();
			Intent myIntent = new Intent(view.getContext(),
					DM_InvoiceMenu.class);
			myIntent.putExtra("TAGID", "SALES");
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(myIntent, 0);
			StockLoadingAlert.dismiss();
			finish();
			return;

		} else {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_Expense_Reimbursement.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("EXPENCE SAVE ERROR");
			// Setting Dialog Message
			alertDialog.setMessage("Current Expence Not Saved...");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}

	}
	public void ExitFromForm(View view) {
		StockLoadingAlert.dismiss();
		if (etexpenseremfno.length() != 0) {
			saveTempExpenseReimbursement();
			Intent myIntent = new Intent(view.getContext(),
					DM_InvoiceMenu.class);
			myIntent.putExtra("TAGID", "SALES");
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(myIntent, 0);
			StockLoadingAlert.dismiss();
			finish();
			return;

		} else {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_Expense_Reimbursement.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("EXPENCE SAVE ERROR");
			// Setting Dialog Message
			alertDialog.setMessage("Current Expence Not Saved...");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}
	}
	// =================================================================
	public void btnPrintStloading(View view) {
		try {
			showDialog(DIALOG_PRINT_STOCK_LOADING);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	// Undo Invoice Handling
	public void btnPrintInvoiceCancel(View view) {
		StockLoadingAlert.dismiss();
	}

	public void btnPrintInvoiceAccept(View view) {
		StockLoadingAlert.dismiss();
	}

	// ==============Undo Invoice====================
	public void btnUndoLoading(View view) {
		if (etexpenseremfno.length() != 0) {
			try {
				showDialog(DIALOG_UNDO_STOCK_LOADING);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} else {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_Expense_Reimbursement.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("SELECT EXPENSE");
			// Setting Dialog Message
			alertDialog.setMessage("Select Valid Expense");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}

	}

	// Undo Invoice Handling
	public void btnUndoInvoiceCancel(View view) {
		// synchdata();
		StockLoadingAlert.dismiss();
	}

	public void btnUndoInvoiceAccept(View view) {
		// updateStLoadUndoState();
		CLEARTAG = 22;
		clearFieldsExpenseReim();
		updateExpenseUndoState();
		StockLoadingAlert.dismiss();
	}

	public void btnUndoInvoiceAcceptExit(View view) {
		// CLEARTAG = 22;
		// clearFieldsExpenseReim();
		EXITTAG = 99;
		updateExpenseUndoState();
	}

	private void updateExpenseUndoState() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		String columsup[] = { "stlrepusername", "stLoadActive" };
		Cursor undoExpenseRecordMain = null;
		try {
			undoExpenseRecordMain = mydb.query(TEMP_DAYEXPENSE_SUMMARY, null,
					"dexprepusername='" + currentUserStLoad
							+ "' AND dexpreActive='9'", null, null, null, null);
		} catch (Exception e) {
		}
		if (undoExpenseRecordMain != null) {
			if (undoExpenseRecordMain.getCount() > 0) {
				while (undoExpenseRecordMain.moveToNext()) {
					ContentValues valueupdateExpense = new ContentValues();
					String stExpenseCurrentid = undoExpenseRecordMain
							.getString(0);
					currentExpenseRefCode = undoExpenseRecordMain.getString(7);
					valueupdateExpense.put("dexpreActive", "9");
					valueupdateExpense.put("dexpreComplete", "0");
					valueupdateExpense.put("amountTot", "0.00");
					valueupdateExpense.put("dexpremark", "");

					mydb.update(TEMP_DAYEXPENSE_SUMMARY, valueupdateExpense,
							"dexpsum_id ='" + stExpenseCurrentid + "'", null);
				}

			}

		}
		undoExpenseRecordMain.close();
		mydb.close();
		deleteExpenseDetailsItems();

	}

	private void deleteExpenseDetailsItems() {
		DELTAG = 88;
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor saveStLoadingItemDel = null;
		try {
			saveStLoadingItemDel = mydb.query(DAYEXPENSE_DETAILS, null,
					"RefNo='" + currentExpenseRefCode + "'", null, null, null,
					null);
		} catch (Exception e) {
		}

		if (saveStLoadingItemDel != null) {
			if (saveStLoadingItemDel.getCount() > 0) {
				while (saveStLoadingItemDel.moveToNext()) {
					String tempRepStLoadrefcode = saveStLoadingItemDel
							.getString(1);
					mydb.delete(DAYEXPENSE_DETAILS, "RefNo ='"
							+ currentExpenseRefCode + "'", null);
				}
			}
		}

		Cursor saveStLoadinghedDel = null;
		try {
			saveStLoadinghedDel = mydb.query(DAYEXPENSE_HEADER, null, "RefNo='"
					+ currentExpenseRefCode + "'", null, null, null, null);
		} catch (Exception e) {
		}

		if (saveStLoadinghedDel != null) {
			if (saveStLoadinghedDel.getCount() > 0) {
				while (saveStLoadinghedDel.moveToNext()) {
					String tempRepStLoadrefcode = saveStLoadinghedDel
							.getString(1);
					mydb.delete(DAYEXPENSE_HEADER, "RefNo ='"
							+ currentExpenseRefCode + "'", null);
				}
			}
		}
		if (EXITTAG == 99) {
			Intent myIntent = new Intent(this, DM_InvoiceMenu.class);
			myIntent.putExtra("TAGID", "SALES");
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(myIntent, 0);
			StockLoadingAlert.dismiss();
			finish();
		} else {
			populateExpenseLoadList();
		}

		saveStLoadinghedDel.close();
		saveStLoadingItemDel.close();
		mydb.close();
	}

	// -------------Cancel Stock Loading-------------------------
	public void btnCanclloading(View view) {
		checkStockLoadSaved();
		if (CANCELTAG == 45) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_Expense_Reimbursement.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("EXPENSE NOT SAVED");
			// Setting Dialog Message
			alertDialog
					.setMessage("Selected Expense Record Not Saved.Select Valid Expense Record To Cancel");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					CANCELTAG = 0;
					alertDialog.dismiss();
				}
			});
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		} else {
			checkItemsAvailable();
			if (STOCKITEMSCHK == 101) {
				if (etexpenseremfno.length() != 0) {
					try {
						ButtonTag = 3;
						showDialog(DIALOG_CANCEL_STOCK_LOADING);
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				} else {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_Expense_Reimbursement.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("SELECT EXPENSE");
					// Setting Dialog Message
					alertDialog.setMessage("Select Valid Expense");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				}
			} else if (STOCKITEMSCHK == 102) {
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_Expense_Reimbursement.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("EXPENSE RECORDS");
				// Setting Dialog Message
				alertDialog.setMessage("No Items For Expences");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
			}
		}

	}

	private void checkItemsAvailable() {
		// TODO Auto-generated method stub
		String currentStLoadCodeRef = etexpenseremfno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor curChkItems = null;
		try {
			curChkItems = mydb.query(DAYEXPENSE_DETAILS, null, "RefNo='"
					+ currentStLoadCodeRef + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (curChkItems != null) {
			if (curChkItems.getCount() > 0) {
				STOCKITEMSCHK = 101;
			} else {
				STOCKITEMSCHK = 102;
			}
		}
		curChkItems.close();
		mydb.close();
	}

	private void checkStockLoadSaved() {
		// TODO Auto-generated method stub
		String CurrentStLoadRefNo = etexpenseremfno.getText().toString();
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor CurrentStLoadRefCur = null;
		try {
			CurrentStLoadRefCur = mydb.query(TEMP_DAYEXPENSE_SUMMARY, null,
					"dexprepusername='" + currentUserStLoad
							+ "' AND dexpreActive='9' AND dexprefnocode ='"
							+ CurrentStLoadRefNo + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (CurrentStLoadRefCur != null) {
			if (CurrentStLoadRefCur.getCount() > 0) {
				while (CurrentStLoadRefCur.moveToNext()) {
					String stLoadActive = CurrentStLoadRefCur.getString(6);
					if (stLoadActive.equals("9")) {
						CANCELTAG = 45;
					}

				}
			}
		}
		CurrentStLoadRefCur.close();
		mydb.close();
	}

	// Undo Invoice Handling
	public void btnCancelInvoiceReject(View view) {
		// synchdata();
		StockLoadingAlert.dismiss();
	}

	public void btnCancelInvoiceAccept(View view) {
		cancelNewStockLoadingRec();
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}

	private void cancelNewStockLoadingRec() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor saveStockLoadingMain = null;
		try {
			saveStockLoadingMain = mydb.query(TEMP_DAYEXPENSE_SUMMARY, null,
					"dexprepusername='" + currentUserStLoad
							+ "' AND dexpreActive !='9'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (saveStockLoadingMain != null) {
			if (saveStockLoadingMain.getCount() > 0) {
				while (saveStockLoadingMain.moveToNext()) {
					ContentValues valueupdateStLoadState = new ContentValues();
					String stExpenseCurrentid = saveStockLoadingMain
							.getString(0);
					valueupdateStLoadState.put("dexpreComplete", "2");
					mydb.update(TEMP_DAYEXPENSE_SUMMARY,
							valueupdateStLoadState, "dexpsum_id ='"
									+ stExpenseCurrentid + "'", null);
					// saveNewStockLoadingRec();

				}

			}
		}
		saveStockLoadingMain.close();
		mydb.close();

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_expense_reimbursement);

		Bundle bundle = getIntent().getExtras();
		TagId = bundle.getString("TAGID");
		// Handling layout controls
		etexpenseremfno = (Button) findViewById(R.id.etexpenseremfno);
		btdmexpenseremselect = (Button) findViewById(R.id.btdmexpenseremselect);

		dmexpenseremadd = (Button) findViewById(R.id.dmexpenseremadd);
		dmexpenseremdelete = (Button) findViewById(R.id.dmexpenseremdelete);
		dmexpenseremupdate = (Button) findViewById(R.id.dmexpenseremupdate);

		etdmexpenseremdate = (EditText) findViewById(R.id.etdmexpenseremdate);
		etdmexpenseremremark = (EditText) findViewById(R.id.etdmexpenseremremark);
		etdmexpenseremname = (EditText) findViewById(R.id.etdmexpenseremname);
		etdmexpenseremamount = (EditText) findViewById(R.id.etdmexpenseremamount);

		dmexpensereimList = (LinearLayout) findViewById(R.id.dmexpensereimList);
		dmstexpensereimdetails = (LinearLayout) findViewById(R.id.dmstexpensereimdetails);
		dmstloadActionButtons = (LinearLayout) findViewById(R.id.dmstloadActionButtons);

		// Main loading functions
		currentUserStLoadChk();// Check Current User
		stLoadingAgentPrefix();// Check Current Agent Prefix
		stLoadingTransType();// Check Current Trans Type
		checkLatestStockUnoadingSerial();// Check Current Stock Loading
		populateExpenseList();// Stock Load Location List
		deviceName();
		// List Stock Loading Location
		btdmexpenseremselect.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				dmexpensereimList.setVisibility(view.VISIBLE);
				dmstexpensereimdetails.setVisibility(view.GONE);
				dmstloadActionButtons.setVisibility(view.GONE);
			}
		});

		// Save Expense Details
		dmexpenseremadd.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (etdmexpenseremname.length() == 0) {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_Expense_Reimbursement.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("SELECT EXPENSE");
					// Setting Dialog Message
					alertDialog.setMessage("Please Select Expense From List..");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				} else if (etdmexpenseremamount.length() == 0) {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_Expense_Reimbursement.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("SELECT AMOUNT");
					// Setting Dialog Message
					alertDialog.setMessage("Please Enter Expense Amount..");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				} else {
					saveExpenseReimbursementDetails();
				}
			}
		});

		// Update Expense Details
		dmexpenseremupdate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				SQLiteDatabase mydb;
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				ContentValues updateExpenseDetails = new ContentValues();
				updateExpenseDetails.put("ExpCode", ExpenseCode);
				updateExpenseDetails.put("Amt", etdmexpenseremamount.getText()
						.toString());
				updateExpenseDetails.put("ExpName", etdmexpenseremname
						.getText().toString());
				mydb.update(DAYEXPENSE_DETAILS, updateExpenseDetails,
						"sdb_id ='" + ExpenseRecid + "'", null);
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_Expense_Reimbursement.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("UPDATE");
				// Setting Dialog Message
				alertDialog.setMessage("Record Updated Successfully");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								dmexpenseremadd.setEnabled(true);
								alertDialog.dismiss();

							}
						});
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				updateExpenseSummary();
			}
		});

		dmexpenseremdelete.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				DELTAG = 88;
				SQLiteDatabase mydb;
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				try {
					mydb.delete(DAYEXPENSE_DETAILS, "sdb_id ='" + ExpenseRecid
							+ "'", null);

					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_Expense_Reimbursement.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("DELETE");
					// Setting Dialog Message
					alertDialog.setMessage("Record Deleted Successfully");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();

								}
							});
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					updateExpenseSummary();

				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Error Occured..",
							Toast.LENGTH_SHORT).show();
				}

				mydb.close();
			}
		});
	}

	private void deviceName() {
		// TODO Auto-generated method stub
		String Model = android.os.Build.MODEL;
		String id = android.os.Build.ID;
		deviceUser = Model + "_" + id;
	}

	protected void saveExpenseReimbursementDetails() {
		// TODO Auto-generated method stub
		SAVETAG = 55;
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		// Check last sequence
		try {
			String query = "SELECT * from FDayExpDet Where RefNo = '"
					+ currentExpenseRefCode + "' order by SeqNo DESC limit 1";
			Cursor chkItemSequence = mydb.rawQuery(query, null);
			if (chkItemSequence != null && chkItemSequence.moveToLast()) {
				countC = chkItemSequence.getCount();
				if (countC != 44) {
					Long SeqNo = chkItemSequence.getLong(3);
					Long currentSeqNo = SeqNo + 1;
					currentSequence = Long.toString(currentSeqNo);
				} else {
					currentSequence = "1";
				}

			} else {
				currentSequence = "1";
			}
			chkItemSequence.close();

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured..",
					Toast.LENGTH_SHORT).show();
		}

		// **********Insert Records to Expense Details**********
		try {
			ContentValues newExpenseRecord = new ContentValues();
			newExpenseRecord.put("RefNo", etexpenseremfno.getText().toString());
			newExpenseRecord.put("TxnDate", etdmexpenseremdate.getText()
					.toString());
			newExpenseRecord.put("SeqNo", currentSequence);
			newExpenseRecord.put("ExpCode", ExpenseCode);

			String ExpenseAmtStr = etdmexpenseremamount.getText().toString();
			double ExpenseAmtValue = Double.parseDouble(ExpenseAmtStr
					.replaceAll("[,]", ""));
			ExpenseAmtValue = Math.round(ExpenseAmtValue * 100) / 100.0d;
			newExpenseRecord.put("Amt", ExpenseAmtValue);
			newExpenseRecord.put("ExpName", etdmexpenseremname.getText()
					.toString());
			mydb.insert(DAYEXPENSE_DETAILS, null, newExpenseRecord);
			updateExpenseSummary();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured..",
					Toast.LENGTH_SHORT).show();
		}
		// **********Insert Records to Expense Header**********
		try {
			ContentValues newExpenseRecordHed = new ContentValues();
			newExpenseRecordHed.put("RefNo", etexpenseremfno.getText()
					.toString());
			newExpenseRecordHed.put("TxnDate", etdmexpenseremdate.getText()
					.toString());
			newExpenseRecordHed.put("RepName", currentUserStLoad);
			newExpenseRecordHed.put("DealCode", repDealCode);
			newExpenseRecordHed.put("CostCode", "000");
			newExpenseRecordHed.put("RepCode", currentUserStLoad);
			newExpenseRecordHed.put("RegCode", currentUserStLoad);
			newExpenseRecordHed.put("AreaCode", "1");
			newExpenseRecordHed.put("Remarks", etdmexpenseremremark.getText()
					.toString());
			newExpenseRecordHed.put("AddUser", currentUserStLoad);
			newExpenseRecordHed.put("AddDate", getCurrentTimeString()
					.toString());
			newExpenseRecordHed.put("AddMach", deviceUser);
			newExpenseRecordHed.put("TranBatch", "0");
			mydb.insert(DAYEXPENSE_HEADER, null, newExpenseRecordHed);
			updateExpenseSummary();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured..",
					Toast.LENGTH_SHORT).show();
		}
	}

	// ******Update Total Expense Amount**********
	private void updateExpenseSummary() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor chkExpenseSummary = null;
		try {
			chkExpenseSummary = mydb.query(TEMP_DAYEXPENSE_SUMMARY, null,
					"dexprepusername='" + currentUserStLoad
							+ "' AND dexpreActive='9'", null, null, null, null);
		} catch (Exception e) {
		}
		if (chkExpenseSummary != null) {
			if (chkExpenseSummary.getCount() > 0) {
				while (chkExpenseSummary.moveToNext()) {
					String currentExpenseId = chkExpenseSummary.getString(0);
					String currentExpenseRefCode = chkExpenseSummary
							.getString(7);
					Cursor chkExpenseDetails = null;
					try {
						chkExpenseDetails = mydb.query(DAYEXPENSE_DETAILS,
								null, "RefNo='" + currentExpenseRefCode + "'",
								null, null, null, null);
					} catch (Exception e) {
					}
					if (chkExpenseDetails != null) {
						if (chkExpenseDetails.getCount() > 0) {
							TotExpenseAmountSummary = 0.0;
							while (chkExpenseDetails.moveToNext()) {
								String totExpenseValueSumStr = chkExpenseDetails
										.getString(5);
								double totExpenseValueSum = Double
										.parseDouble(totExpenseValueSumStr);
								TotExpenseAmountSummary = TotExpenseAmountSummary
										+ totExpenseValueSum;
							}
						}
					}

					ContentValues updateExpenseSummary = new ContentValues();

					updateExpenseSummary.put("amountTot",
							TotExpenseAmountSummary);
					mydb.update(TEMP_DAYEXPENSE_SUMMARY, updateExpenseSummary,
							"dexpsum_id ='" + currentExpenseId + "'", null);
				}
			}
		}
		populateExpenseLoadList();
	}

	// Stock Load Items List
	private void populateExpenseList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.listviewdmexpensereimList);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
		int[] totrdes = new int[] { R.id.invexpensename, R.id.invexpensedesc };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowtypedes = null;
		try {
			allrowtypedes = mydb.query(USER_EXPENSE, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}
		if (allrowtypedes != null) {
			if (allrowtypedes.getCount() > 0) {
				while (allrowtypedes.moveToNext()) {
					String ExpCode = allrowtypedes.getString(1);
					String ExpGrpCode = allrowtypedes.getString(2);
					String ExpName = allrowtypedes.getString(3);
					String RecordId = allrowtypedes.getString(4);

					String rawexpensedet = ExpCode + "/" + ExpGrpCode + "/"
							+ ExpName + "/" + RecordId;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", ExpName);
					maptrdes.put("coldes_2", rawexpensedet);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_expense_list_raw, fromtrdes,
						totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		allrowtypedes.close();
		mydb.close();
	}

	// Check Current User
	private void currentUserStLoadChk() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentuserLoad = null;
		try {
			selectCurrentuserLoad = mydb.query(USER_SETTINGS, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentuserLoad != null) {
			if (selectCurrentuserLoad.getCount() > 0) {
				while (selectCurrentuserLoad.moveToNext()) {
					currentUserStLoad = selectCurrentuserLoad.getString(1);
					currentUserPrefixLoad = selectCurrentuserLoad.getString(2);
					currentUserLocation = selectCurrentuserLoad.getString(3);

				}
			}
		}
		selectCurrentuserLoad.close();
		mydb.close();
	}

	// Check Current Agent Prefix
	private void stLoadingAgentPrefix() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectAgentPreType = null;

		try {
			selectAgentPreType = mydb.query(ITEM_CONTROL, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectAgentPreType != null) {
			if (selectAgentPreType.getCount() > 0) {
				while (selectAgentPreType.moveToNext()) {
					stlAgentPrefixType = selectAgentPreType.getString(18);
					repDealCode = selectAgentPreType.getString(19);
				}

			}
		}
		selectAgentPreType.close();
		mydb.close();
	}

	// Check Current Trans Type
	private void stLoadingTransType() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectTransType = null;

		try {
			selectTransType = mydb.query(ITEM_COMPANY_SETTING, null, null,
					null, null, null, null);
		} catch (Exception e) {
		}
		if (selectTransType != null) {
			if (selectTransType.getCount() > 0) {
				while (selectTransType.moveToNext()) {
					String cSettingsCode = selectTransType.getString(1);
					String cCharValue = selectTransType.getString(4);
					if (cSettingsCode.equals("DAYEX")) {
						StlTransTypePrefix = cCharValue.trim();
					}
				}
			}
		}
		selectTransType.close();
		mydb.close();
	}

	private void checkLatestStockUnoadingSerial() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectInvoiceSerial = null;

		try {
			selectInvoiceSerial = mydb.query(INV_COMPANY_BRANCH, null,
					"cSettingsCode='DAYEX' AND BranchCode='"
							+ currentUserStLoad + "'", null, null, null, null);
		} catch (Exception e) {
		}

		Cursor selectLastinvrec = null;
		try {
			selectLastinvrec = mydb.query(TEMP_DAYEXPENSE_SUMMARY, null,
					"dexprepusername='" + currentUserStLoad
							+ "' AND dexpreActive='9'", null, null, null, null);
		} catch (Exception e) {
		}

		if (selectInvoiceSerial != null) {
			if (selectInvoiceSerial.getCount() > 0) {
				while (selectInvoiceSerial.moveToNext()) {
					String cSettingsCode = selectInvoiceSerial.getString(3);
					String nNumVal = selectInvoiceSerial.getString(4);
					tempRepExpenseSerialStr = nNumVal.trim();
					if (selectLastinvrec != null) {
						if (selectLastinvrec.getCount() > 0) {
							if (selectLastinvrec.moveToLast()) {
								viewCurrentExpenseDetails();
							}
						} else if (selectLastinvrec.getCount() <= 0) {
							saveTempExpenseReimbursement();// Save Store Loading
						}
					}

				}
			} else {
				tempRepExpenseSerialStr = "1";
				try {
					ContentValues newAdjustment = new ContentValues();
					newAdjustment.put("BranchCode", currentUserStLoad);
					newAdjustment.put("RecordId", "1");
					newAdjustment.put("cSettingsCode", "DAYEX");
					newAdjustment.put("nNumVal", tempRepExpenseSerialStr);
					mydb.insert(INV_COMPANY_BRANCH, null, newAdjustment);
					saveTempExpenseReimbursement();// Save Store Loading

				} catch (Exception e) {
					Toast.makeText(this, e.toString(), Toast.LENGTH_LONG)
							.show();
				}
				mydb.close();
			}
		}
		selectInvoiceSerial.close();
		mydb.close();
	}

	// **************save Temp Expense Reimbursement********************
	private void saveTempExpenseReimbursement() {
		Log.v(TAG, "saveTempExpenseReimbursement:"+ tempRepExpenseSerialStr);
		// TODO Auto-generated method stub
		RepExpenseCode = StlTransTypePrefix.trim() + stlAgentPrefixType.trim()
				+ currentUserPrefixLoad;
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			ContentValues saveStockLoadSummary = new ContentValues();
			saveStockLoadSummary.put("dexprepusername", currentUserStLoad);
			saveStockLoadSummary.put("dexprepprefix", currentUserPrefixLoad);
			saveStockLoadSummary
					.put("dexprefnoserial", tempRepExpenseSerialStr);
			saveStockLoadSummary.put("dexprefcode", RepExpenseCode);

			try {
				if (tempRepExpenseSerialStr.length() == 1) {
					String newInvNumberStr = "00000" + tempRepExpenseSerialStr;
					currentExpenseRefCode = RepExpenseCode.trim() + "/"
							+ newInvNumberStr;
				} else if (tempRepExpenseSerialStr.length() == 2) {
					String newInvNumberStr = "0000" + tempRepExpenseSerialStr;
					currentExpenseRefCode = RepExpenseCode.trim() + "/"
							+ newInvNumberStr;
				} else if (tempRepExpenseSerialStr.length() == 3) {
					String newInvNumberStr = "000" + tempRepExpenseSerialStr;
					currentExpenseRefCode = RepExpenseCode.trim() + "/"
							+ newInvNumberStr;
				} else if (tempRepExpenseSerialStr.length() == 4) {
					String newInvNumberStr = "00" + tempRepExpenseSerialStr;
					currentExpenseRefCode = RepExpenseCode.trim() + "/"
							+ newInvNumberStr;
				} else if (tempRepExpenseSerialStr.length() == 5) {
					String newInvNumberStr = "0" + tempRepExpenseSerialStr;
					currentExpenseRefCode = RepExpenseCode.trim() + "/"
							+ newInvNumberStr;
				} else {
					String newInvNumberStr = tempRepExpenseSerialStr;
					currentExpenseRefCode = RepExpenseCode.trim() + "/"
							+ newInvNumberStr;
				}
			} catch (Exception e) {

			}
			saveStockLoadSummary.put("dexprefnocode", currentExpenseRefCode);
			saveStockLoadSummary.put("dexpremark", "");
			saveStockLoadSummary.put("dexpreComplete", "0");
			saveStockLoadSummary.put("dexpreActive", "9");
			saveStockLoadSummary.put("amountTot", "0.00");
			mydb.insert(TEMP_DAYEXPENSE_SUMMARY, null, saveStockLoadSummary);
			updateFcompanyBranch();

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Record Not Insert..",
					Toast.LENGTH_SHORT).show();
		}
		mydb.close();
		viewCurrentExpenseDetails();
	}

	private void updateFcompanyBranch() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectUserSerial = null;

		try {
			selectUserSerial = mydb.query(INV_COMPANY_BRANCH, null,
					"cSettingsCode='DAYEX' AND BranchCode='"
							+ currentUserStLoad + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (selectUserSerial != null) {
			if (selectUserSerial.getCount() > 0) {
				if (selectUserSerial.moveToLast()) {
					ContentValues updateNewSerial = new ContentValues();
					String serialStId = selectUserSerial.getString(0);
					updateNewSerial.put("nNumVal", tempRepExpenseSerialStr);
					mydb.update(INV_COMPANY_BRANCH, updateNewSerial,
							"fcombra_id ='" + serialStId + "'", null);
				}
			}
		}

	}

	// **************view Current Expense Details********************
	private void viewCurrentExpenseDetails() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor selectCurrentStockLoad = null;
		try {
			selectCurrentStockLoad = mydb.query(TEMP_DAYEXPENSE_SUMMARY, null,
					"dexprepusername='" + currentUserStLoad
							+ "' AND dexpreActive='9'", null, null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentStockLoad != null) {
			if (selectCurrentStockLoad.getCount() > 0) {
				if (selectCurrentStockLoad.moveToLast()) {
					currentExpenseRefCode = selectCurrentStockLoad.getString(7);
					etexpenseremfno.setText(currentExpenseRefCode);
					etdmexpenseremdate.setText(getCurrentTimeString()
							.toString());
					populateExpenseLoadList(); // List current invoice items
				}
			}
		}
		selectCurrentStockLoad.close();
		mydb.close();
	}

	private void populateExpenseLoadList() {
		// TODO Auto-generated method stub
		SimpleAdapter adaptertrdes = null;
		ListView lvtypedes = (ListView) findViewById(R.id.dmexpensedetailslist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "colstloaddes_1", "colstloaddes_2",
				"colstloaddes_3" };
		int[] totrdes = new int[] { R.id.expenserawdetails, R.id.expenseValue,
				R.id.btnexpenserawdetails };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowexpensedes = null;
		String columsup[] = { "refInvoiceDetCode" };
		String col = "ItemCode";
		try {
			allrowexpensedes = mydb.query(DAYEXPENSE_DETAILS, null, "RefNo='"
					+ currentExpenseRefCode + "'", null, null, null, null);

		} catch (Exception e) {
		}
		if (allrowexpensedes != null) {
			if (allrowexpensedes.getCount() > 0) {
				while (allrowexpensedes.moveToNext()) {
					//RefNo ,TxnDate ,SeqNo ,ExpCode ,Amt ,ExpName

					String expenseid = allrowexpensedes.getString(0);
					String TxnDate = allrowexpensedes.getString(2);
					String Amt = allrowexpensedes.getString(5);
					String ExpName = allrowexpensedes.getString(6);

					String rawitemsdet = expenseid + "-" + TxnDate + "-" + Amt
							+ "-" + ExpName;

					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("colstloaddes_1", ExpName);
					maptrdes.put("colstloaddes_2", Amt);
					maptrdes.put("colstloaddes_3", rawitemsdet);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				adaptertrdes = new SimpleAdapter(this, fillMapstrdes,
						R.layout.dm_expense_details_list_raw, fromtrdes,
						totrdes);

				lvtypedes.setAdapter(adaptertrdes);
			}
			int recRemCount = allrowexpensedes.getCount();
			if (recRemCount == 0 && DELTAG == 88) {
				Intent myIntent = new Intent(this,
						DM_Expense_Reimbursement.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				myIntent.putExtra("TAGID", "3");
				startActivityForResult(myIntent, 0);
				DELTAG = 0;
				finish();
				return;
			} else if (recRemCount == 0 && CLEARTAG == 22) {
				Intent myIntent = new Intent(this,
						DM_Expense_Reimbursement.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				myIntent.putExtra("TAGID", "3");
				startActivityForResult(myIntent, 0);
				CLEARTAG = 0;
				finish();
				return;
			}
		}
		clearFieldsExpenseReim();
		allrowexpensedes.close();
		mydb.close();
	}

	private void clearFieldsExpenseReim() {
		// TODO Auto-generated method stub
		etdmexpenseremname.setText("");
		etdmexpenseremamount.setText("");

	}

	// ******retrieve current date and time***********************
	private String getCurrentTimeString() {
		// 2013-10-04 00:00:00.000
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd/MM/yyyy");
		String date_to_string = ddMMMyyFormat.format(dateNow);
		return date_to_string;
	}

	// **********Handling Dialog Box Functions*******************
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_SAVE_STOCK_LOADING:
			LayoutInflater inflater = LayoutInflater.from(this);
			View dialogview = inflater.inflate(
					R.layout.dm_dialog_save_adjustment, null);

			AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
			dialogbuilder.setTitle("Save Expense Reimbursement...");
			dialogbuilder.setView(dialogview);
			StockLoadingAlert = dialogbuilder.create();
			StockLoadingAlert.setCanceledOnTouchOutside(false);
			break;
		case DIALOG_CANCEL_STOCK_LOADING:
			LayoutInflater inflaterstl = LayoutInflater.from(this);
			View dialogviewstl = inflaterstl.inflate(
					R.layout.dm_dialog_cancel_invoice, null);

			AlertDialog.Builder dialogbuilderstl = new AlertDialog.Builder(this);
			dialogbuilderstl.setTitle("Cancel Expense Reimbursement...");
			dialogbuilderstl.setView(dialogviewstl);
			StockLoadingAlert = dialogbuilderstl.create();
			StockLoadingAlert.setCanceledOnTouchOutside(false);
			break;

		case DIALOG_UNDO_STOCK_LOADING:
			LayoutInflater inflateru = LayoutInflater.from(this);
			View dialogviewu = inflateru.inflate(
					R.layout.dm_dialog_undo_invoice, null);

			AlertDialog.Builder dialogbuilderu = new AlertDialog.Builder(this);
			dialogbuilderu.setTitle("Undo Current Expense Reimbursement...");
			dialogbuilderu.setView(dialogviewu);
			StockLoadingAlert = dialogbuilderu.create();
			StockLoadingAlert.setCanceledOnTouchOutside(false);
			break;
		case DIALOG_PRINT_STOCK_LOADING:
			LayoutInflater inflaterp = LayoutInflater.from(this);
			View dialogviewp = inflaterp.inflate(
					R.layout.dm_dialog_print_invoice, null);

			AlertDialog.Builder dialogbuilderp = new AlertDialog.Builder(this);
			dialogbuilderp.setTitle("Printing Configuration Failure...");
			dialogbuilderp.setView(dialogviewp);
			StockLoadingAlert = dialogbuilderp.create();
			StockLoadingAlert.setCanceledOnTouchOutside(false);
			break;
		}

		return StockLoadingAlert;

	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}

}
